package com.probox.common.entity.service.platfom.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.domain.R;
import com.probox.common.core.enums.PlatformSettingEnum;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.redis.service.RedisService;
import com.probox.common.entity.service.common.SysReginService;
import com.probox.common.entity.service.order.IOrderShipAutoService;
import com.probox.order.api.domain.OrderShipAutoVo;
import com.probox.platform.api.domain.PlatformGeneralsettingsVo;
import com.probox.common.entity.domain.platfom.PlatformInfo;
import com.probox.common.entity.domain.platfom.PlatformTemplate;
import com.probox.common.entity.service.platfom.IPlatformInfoService;
import com.probox.common.entity.service.platfom.IPlatformTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.platfom.PlatformGeneralsettingsMapper;
import com.probox.common.entity.domain.platfom.PlatformGeneralsettings;
import com.probox.common.entity.service.platfom.IPlatformGeneralsettingsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 平台_店铺通用设置Service业务层处理
 *
 * @author usoft
 * @date 2021-07-08
 */
@Service
@Transactional
public class PlatformGeneralsettingsServiceImpl extends ServiceImpl<PlatformGeneralsettingsMapper, PlatformGeneralsettings> implements IPlatformGeneralsettingsService {
    @Autowired
    private PlatformGeneralsettingsMapper platformGeneralsettingsMapper;

    @Autowired
    private IPlatformInfoService iPlatformInfoService;

    @Autowired
    private IPlatformTemplateService iPlatformTemplateService;

    @Autowired
    private RedisService redisService;


    @Autowired
    private IOrderShipAutoService shipAutoService;

    @Autowired
    private SysReginService sysReginService;


    /**
     * 查询平台_店铺通用设置
     *
     * @param generalsettingsUid 平台_店铺通用设置ID
     * @return 平台_店铺通用设置
     */
    @Override
    public PlatformGeneralsettings selectPlatformGeneralsettingsById(Long generalsettingsUid) {
        return this.getById(generalsettingsUid);
    }

    /**
     * 查询平台_店铺通用设置
     */
    @Override
    public PlatformGeneralsettingsVo get(Long uid) {
        String key = CachePrefix.PLATFORM_GENERAL_SETTINGS + uid;
        PlatformGeneralsettingsVo vo = redisService.getCacheObject(key);
        if (ObjectUtil.isEmpty(vo)) {
            QueryWrapper<PlatformGeneralsettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PLATFORM_UID", uid);
            PlatformGeneralsettings platformGeneralsettings = platformGeneralsettingsMapper.selectOne(queryWrapper);
            if (ObjectUtil.isEmpty(platformGeneralsettings)) throw new BaseException("数据有误,请联系管理员！");
            vo = new PlatformGeneralsettingsVo();
            vo.setGoodsImg("http://resource.tkmall.tongkeer.com/shop/maokun/208fcaf3a6ed41f088198301d1ce8849_210713185651");
            BeanUtils.copyProperties(platformGeneralsettings, vo);
            JSONObject jsonObject = JSON.parseObject(platformGeneralsettings.getCustomerserviceGoodsConfig());
            HashMap defaultMap = new HashMap();
            defaultMap.put("default", jsonObject.get("default"));
            defaultMap.put("label", jsonObject.get("label"));
            vo.setCustomerserviceGoodsConfigMap(defaultMap);
            defaultMap = new HashMap();
            jsonObject = JSON.parseObject(platformGeneralsettings.getCustomerserviceOrderConfig());
            defaultMap.put("default", jsonObject.get("default"));
            defaultMap.put("label", jsonObject.get("label"));
            vo.setCustomerserviceOrderConfigMap(defaultMap);
            defaultMap = new HashMap();
            jsonObject = JSON.parseObject(platformGeneralsettings.getCommentService());
            defaultMap.put("show", jsonObject.get("show"));
            defaultMap.put("rate", jsonObject.get("rate"));
            vo.setCommentServiceMap(defaultMap);
            defaultMap = new HashMap();
            jsonObject = JSON.parseObject(platformGeneralsettings.getCommentProduct());
            defaultMap.put("show", jsonObject.get("show"));
            defaultMap.put("rate", jsonObject.get("rate"));
            vo.setCommentProductMap(defaultMap);
            defaultMap = new HashMap();
            jsonObject = JSON.parseObject(platformGeneralsettings.getCommentLogistics());
            defaultMap.put("show", jsonObject.get("show"));
            defaultMap.put("rate", jsonObject.get("rate"));
            vo.setCommentLogisticsMap(defaultMap);
            defaultMap = new HashMap();
            jsonObject = JSON.parseObject(platformGeneralsettings.getGoodsSaleNumber());
            defaultMap.put("show", jsonObject.get("show"));
            defaultMap.put("number", jsonObject.get("number"));
            vo.setGoodsSaleNumberMap(defaultMap);
            OrderShipAutoVo data = shipAutoService.getShipAuto(uid);
            if (ObjectUtil.isNotEmpty(data)) {
                vo.setAutoDate(data.getAutoDate());
                vo.setDelayedDate(data.getDelayedDate());
                vo.setAutoUid(Long.valueOf(data.getAutoUid()));
            }
            // 获取热门标签
            String hotSearch = platformGeneralsettings.getHotSearch();
            if (ObjectUtil.isNotEmpty(hotSearch)) {
                vo.setHotSearchs(hotSearch.split(","));
            }
            // 获得平台信息
            String[] labels = new String[3];
            PlatformInfo platformInfo = iPlatformInfoService.getById(uid);
            if (ObjectUtil.isNotEmpty(platformInfo)) {
                BeanUtils.copyProperties(platformInfo, vo);
                if (ObjectUtil.isNotEmpty(platformInfo.getPlatformProvince())) {
                    labels[0] = platformInfo.getPlatformProvince();
                    labels[1] = platformInfo.getPlatformCity();
                    labels[2] = platformInfo.getPlatformArea();
                    Long[] reginCode = sysReginService.getReginCode(labels);
                    vo.setRegion(reginCode);
                }
            }
            //获取模板信息
            List<PlatformTemplate> templatePage = iPlatformTemplateService.getTemplatePageStatus(uid);
            if (ObjectUtil.isNotEmpty(templatePage)) BeanUtils.copyProperties(templatePage.get(0), vo);
            redisService.setCacheObject(key, vo, 30L, TimeUnit.DAYS);
        }
        if (ObjectUtil.isEmpty(vo.getPlatformName())) {
            PlatformInfo platformInfo = iPlatformInfoService.getById(uid);
            if (ObjectUtil.isNotEmpty(platformInfo)) {
                BeanUtils.copyProperties(platformInfo, vo);
                redisService.setCacheObject(key, vo, 30L, TimeUnit.DAYS);
            }
        }
        return vo;
    }

    /**
     * 新增平台_店铺通用设置
     *
     * @param uid 平台_店铺通用设置
     * @return 结果
     */
    @Override
    public boolean insertPlatformGeneralsettings(Long uid) {
        HashMap map = new HashMap();
        map.put("default", "0");
        map.put("label", "");
        JSONObject jsonObj = new JSONObject(map);
        String defaultMap = jsonObj.toJSONString();
        map = new HashMap();
        map.put("show", "0");
        map.put("rate", "");
        jsonObj = new JSONObject(map);
        String rate = jsonObj.toJSONString();
        map = new HashMap();
        map.put("show", "0");
        map.put("number", "");
        jsonObj = new JSONObject(map);
        String number = jsonObj.toJSONString();
        PlatformGeneralsettings settings = new PlatformGeneralsettings(uid, PlatformSettingEnum.show.getKey(),
                PlatformSettingEnum.hide.getKey(), defaultMap, rate, number, "60", "60",
                SecurityUtils.getUserId(), SecurityUtils.getUsername(), DateUtil.date());
        return this.save(settings);

    }

    /**
     * 修改平台_店铺通用设置
     *
     * @param vo 平台_店铺通用设置
     * @return 结果
     */
    @Override
    public boolean updatePlatformGeneralsettings(PlatformGeneralsettingsVo vo) {
        if (ObjectUtil.isEmpty(vo)) throw new BaseException("数据有问题,请联系管理员");
        PlatformGeneralsettings settings = new PlatformGeneralsettings();
        BeanUtils.copyProperties(vo, settings);
        JSONObject jsonObj = new JSONObject(vo.getCustomerserviceGoodsConfigMap());
        settings.setCustomerserviceGoodsConfig(jsonObj.toJSONString());
        jsonObj = new JSONObject(vo.getCustomerserviceOrderConfigMap());
        settings.setCustomerserviceOrderConfig(jsonObj.toJSONString());
        jsonObj = new JSONObject(vo.getCommentServiceMap());
        settings.setCommentService(jsonObj.toJSONString());
        jsonObj = new JSONObject(vo.getCommentProductMap());
        settings.setCommentProduct(jsonObj.toJSONString());
        jsonObj = new JSONObject(vo.getCommentLogisticsMap());
        settings.setCommentLogistics(jsonObj.toJSONString());
        jsonObj = new JSONObject(vo.getGoodsSaleNumberMap());
        settings.setGoodsSaleNumber(jsonObj.toJSONString());
        if (ObjectUtil.isNotEmpty(vo.getHotSearchs())) {
            StringBuffer tags = new StringBuffer("");
            String[] hotSearchs = vo.getHotSearchs();
            for (int i = 0; i < hotSearchs.length; i++) {
                tags.append(hotSearchs[i] + ",");
            }
            if (!"".equals(tags.toString())) {
                String s = tags.toString();
                s = s.substring(0, s.length() - 1);
                settings.setHotSearch(s);
            } else settings.setHotSearch("");
        } else settings.setHotSearch("");
        this.updateById(settings);
        PlatformInfo info = new PlatformInfo();
        BeanUtils.copyProperties(vo, info);
        iPlatformInfoService.updatePlatformInfo(info);
        OrderShipAutoVo shipAutoVo = new OrderShipAutoVo();
        shipAutoVo.setPlatformUid(vo.getPlatformUid());
        if (vo.getAutoUid() != null) {
            shipAutoVo.setAutoUid(vo.getAutoUid().intValue());
        }
        shipAutoVo.setAutoDate(vo.getAutoDate());
        shipAutoVo.setDelayedDate(vo.getDelayedDate());
        shipAutoVo.setUpdateUser(SecurityUtils.getUserId());
        shipAutoVo.setUpdateName(SecurityUtils.getUsername());
        shipAutoVo.setUpdateTime(DateUtil.date());
        boolean b = shipAutoService.addShipAuto(shipAutoVo);
        if (b == false) throw new BaseException("请联系管理员！");
        redisService.deleteObject(CachePrefix.PLATFORM_GENERAL_SETTINGS + vo.getPlatformUid());
        return true;
    }

    /**
     * 批量删除平台_店铺通用设置
     *
     * @param generalsettingsUids 需要删除的平台_店铺通用设置ID
     * @return 结果
     */
    @Override
    public boolean deletePlatformGeneralsettingsByIds(Long[] generalsettingsUids) {
        return this.removeByIds(Arrays.asList(generalsettingsUids));
    }


}
